package cn.tedu.charging.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    /**
     * static 属性, 减少每次调用时创建对象, 提升效率,jvm在初始化的JsonUtils会创建 ObjectMapper的实例
     * 只创建一个 objectMapper实例
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object object) {
        try {
            //没有必要每次调用toJson方法时都创建  ObjectMapper objectMapper
            //占用空间, 所以使用单例模式
            //ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 把json转换为对象
     * @param json 具体的json字符串
     * @param clazz 对象的类型
     * @return
     * @param <T>
     */

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            //ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
